package com.by.config;


import com.by.bean.ShopCartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class RedisUtils {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    private static final String CART_KEY_PREFIX = "shopping_cart:";

    // 设置购物车商品列表到Redis
    public void setCartItems(String userId, List<ShopCartItem> cartItems, long timeout) {
            String key = CART_KEY_PREFIX + userId;
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        for (ShopCartItem item : cartItems) {
            String itemKey = "item:" + item.getCartItemId();
            hashOperations.put(key, itemKey, item);
        }
    }

    // 从Redis获取购物车商品列表
    public List<ShopCartItem> getCartItems(String userId) {
        String key = CART_KEY_PREFIX + userId;
        HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
        Map<String, Object> entries = hashOperations.entries(key);
        List<ShopCartItem> cartItems = new ArrayList<>();
        for (Object value : entries.values()) {
            if (value instanceof ShopCartItem) {
                cartItems.add((ShopCartItem) value);
            }
        }
        return cartItems;

    }

    // 删除Redis中购物车相关数据
    public void deleteCartItems(String userId) {
        String key = CART_KEY_PREFIX + userId;
        redisTemplate.delete(key);
    }

    // 修改购物车中商品的数量
    public void updateCartItemCount(String userId, Long cartItemId, int delta) {
        String key = CART_KEY_PREFIX + userId;
        HashOperations<String, String, Object> hashOps = redisTemplate.opsForHash();
        String itemKey = "item:" + cartItemId;
        ShopCartItem item = (ShopCartItem) hashOps.get(key, itemKey);
        if (item != null) {
            item.setCount(item.getCount() + delta); // 调整数量
            hashOps.put(key, itemKey, item); // 重新存回Redis
        }
    }

}

